package com.pbxadmin.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SecurityHandler implements HandlerInterceptor{
	
	private Logger log = LoggerFactory.getLogger(SecurityHandler.class);
	
	public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception arg3) throws Exception {
		
	}

	public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView arg3) throws Exception {
		
	}

	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
		//log.debug(">>>> SecurityHandler");
		//log.debug(">>>> requestURI:{}", req.getRequestURI());
		
		String requestURI = req.getRequestURI();
		if(requestURI.equals("/pbxadmin") || requestURI.equals("/pbxadmin/") || requestURI.endsWith("/pbxadmin/login") || requestURI.endsWith("/pbxadmin/logout") || requestURI.endsWith("/pbxadmin/login.html")){
			return true;
		}
		
		//log.debug("SecurityHandler validate ... requestURI:{}",requestURI);
		
		HttpSession session = req.getSession();
		if(session != null){
			if(session.getAttribute("login") != null){
				String flag = (String)session.getAttribute("login");
				if(flag.equals("Y")){
					return true;
				}
			}
		}
		//log.debug(">>>> need login...");
		req.setAttribute("message", "this action need login");
		req.getRequestDispatcher("/login?url="+requestURI).forward(req, resp);
		return false;
	}

}
